/* eslint-disable no-var */
import React, { useState, useEffect, useRef } from "react";
import * as THREE from 'three';


import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"

import { ShaderPass } from 'three/examples/jsm/postprocessing/ShaderPass';

import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer'; //EffectComposer 效果组合器
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass'; // RenderPass 处理通道
import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass';//UnrealBloomPass 泛光通道

import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js'; // FBX 模型加载器

const  About=() =>{
  const BLOOM_SCENE =useRef(1).current;

  const bloomLayer =useRef(new THREE.Layers()).current  ;
  bloomLayer.set(BLOOM_SCENE);

  const params = {
    exposure: 1,
    bloomStrength: 5,
    bloomThreshold: 0,
    bloomRadius: 0,
    scene: 'Scene with Glow'
  };

  const scene =useRef(new THREE.Scene()).current ;

  const camera =useRef(new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 200)).current ;


  const darkMaterial =useRef(new THREE.MeshBasicMaterial({ color: 'black' })).current ;
  const materials:any =useRef({}).current;

  const renderer =useRef(new THREE.WebGLRenderer({ antialias: true })).current ;//是否执行抗锯齿。默认为false.
  const controls =useRef(new OrbitControls(camera, renderer.domElement)).current ;
  const renderScene =useRef( new RenderPass(scene, camera)).current;

  const bloomPass =useRef(new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 1.5, 0.4, 0.85)).current ;


 
  
 
  renderer.setPixelRatio(window.devicePixelRatio); //设置设备像素比。通常用于避免HiDPI设备上绘图模糊
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.toneMapping = THREE.ReinhardToneMapping; //色调映射

 
  useEffect(()=>{
    document.body.appendChild(renderer.domElement);
   
    
  },[renderer])

  
  camera.position.set(0, 0, 20);
  camera.lookAt(0, 0, 0);

 
  controls.maxPolarAngle = Math.PI * 0.5;
  controls.minDistance = 1;
  controls.maxDistance = 100;
  controls.addEventListener('change', render);

  scene.add(new THREE.AmbientLight(0x404040));

 
  bloomPass.threshold = params.bloomThreshold;
  bloomPass.strength = params.bloomStrength;
  bloomPass.radius = params.bloomRadius;

  const bloomComposer = new EffectComposer(renderer);
  bloomComposer.renderToScreen = false;
  bloomComposer.addPass(renderScene);
  bloomComposer.addPass(bloomPass);

  const finalPass = new ShaderPass(
    new THREE.ShaderMaterial({
      uniforms: {
        baseTexture: { value: null },
        bloomTexture: { value: bloomComposer.renderTarget2.texture }
      },
      vertexShader: `varying vec2 vUv;

          void main() {
    
            vUv = uv;
    
            gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
    
          }`,
      fragmentShader: `uniform sampler2D baseTexture;
          uniform sampler2D bloomTexture;
    
          varying vec2 vUv;
    
          void main() {
    
            gl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) );
    
          }`,
      defines: {}
    }), 'baseTexture'
  );
  finalPass.needsSwap = true;

  const finalComposer = new EffectComposer(renderer);
  finalComposer.addPass(renderScene);
  finalComposer.addPass(finalPass);

  const raycaster = new THREE.Raycaster();

  const mouse = new THREE.Vector2();

  window.addEventListener('pointerdown', onPointerDown);


  setupScene();

  function onPointerDown(event:any) {
    

    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;

  

    raycaster.setFromCamera(mouse, camera);
    const intersects = raycaster.intersectObjects(scene.children, false);
    if (intersects.length > 0) {
      

      const object = intersects[0].object;
      object.layers.toggle(BLOOM_SCENE);
      render();

    }

  }

  window.onresize = function () {

    const width = window.innerWidth;
    const height = window.innerHeight;

    camera.aspect = width / height;
    camera.updateProjectionMatrix();

    renderer.setSize(width, height);

    bloomComposer.setSize(width, height);
    finalComposer.setSize(width, height);

    render();

  };

  function setupScene() {
    scene.children.length = 0;
    const color = new THREE.Color();
    color.setHSL(Math.random(), 0.7, Math.random() * 0.2 + 0.05);
    const geometry = new THREE.BoxGeometry( 1, 1, 1 );
		const material = new THREE.MeshBasicMaterial( {  color: color } );
		const cube = new THREE.Mesh( geometry, material );
		scene.add( cube );

    render();

  }



  function render() {
    switch (params.scene) {

     
      case 'Scene with Glow':
      default:

      console.log(params.scene,'params.scene dao  这里一i')
      
        // render scene with bloom 使用开花渲染场景
        renderBloom(true);

        // render the entire scene, then render bloom scene on top 渲染整个场景，然后在顶部渲染开花场景
        finalComposer.render();
        break;

    }
  }
  function renderBloom(mask:any) {
    if (mask === true) {
      console.log(scene,'SceneSceneScene ------------->')
      scene.traverse(item=>{
        // console.log(item.layers, item,'-----------------> zheg这个 看看 为什么');
        darkenNonBloomed(item)
      });
      bloomComposer.render();
      scene.traverse(restoreMaterial);
    }
  }
 
  function darkenNonBloomed(obj:any,index:any=0) {
    // console.log(obj, ' 你 这么就拿到数据了',obj.isMesh , bloomLayer.test(obj.layers) === false,obj.layers);
 
    if (obj.isMesh && bloomLayer.test(obj.layers) === false) {
     
      materials[obj.uuid] = obj.material;
      obj.material = darkMaterial;
      
      console.log('12312----------------->>>', obj);
      console.log('12312----------------->>>', darkMaterial);
      console.log('12312----------------->>>', materials[obj.uuid]);

    }

  }

  function restoreMaterial(obj:any) {

    if (materials[obj.uuid]) {

      obj.material = materials[obj.uuid];
      delete materials[obj.uuid];

    }

  }


  return (
   <></>
  );
}

export default About
